import Vue from 'vue'
import Vuex from 'vuex'

// 1.安装插件
Vue.use(Vuex)

// 2.创建对象
const store = new Vuex.Store({
  state: {
    // 保存状态
    counter: 0,
    students: [
      { id: 1, name: 'aa', age: 18 },
      { id: 2, name: 'zhangsan', age: 22 },
      { id: 3, name: 'lisi', age: 21 },
      { id: 4, name: 'peter', age: 10 },
      { id: 5, name: 'kugou', age: 30 }
    ]
  },
  mutations: {
    // VUEX的store状态的更新唯一方式：提交mutation
    // 方法

    increase (state) {
      state.counter++
    },
    decrease (state) {
      state.counter--
    },
    // 传参数
    increaseCount (state, count) {
      // 参数叫做payload 负载
      state.counter = state.counter + count
    },
    // 传参数payload
    decreaseCount (state, payload) {
      // 参数叫做payload 负载
      state.counter = state.counter - payload.count
    },
    // 传参数对象
    addstudent (state, stu) {
      state.students.push(stu)
    }
  },
  actions: {
    // 异步操作用来替代mutation
    // context:上下文 等于store对象
    aincrease (context) {
      setTimeout(() => {
        context.commit('increase')
      }, 2000)
    },
    aincreaseCounter (context, count) {
      return new Promise((resolve, reject) => {
        // 第二次网络请求的代码
        setTimeout(() => {
          context.commit('increaseCount', count)
          resolve('111')
        }, 1000)
      })
    }
  },
  getters: {
    // 计算方法
    powerCounter (state) {
      return state.counter * state.counter
    },
    more20stu (state) {
      return state.students.filter(s => {
        return s.age > 20
      })
    },
    more20stuleng (state, getters) {
      return getters.more20stu.length
    },
    moreAgestu (state) {
      // 传参数的话要返回一个函数

      // return function (age) {
      //   return state.students.filter(s => s.age > age)
      // }
      return age => {
        return state.students.filter(s => s.age > age)
      }
    }
  },
  modules: {}
})

// 3.导出store对象
export default store
